import { watch, onMounted, onBeforeMount, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import useStore from '@/stores'
const { App } = useStore()

const { body } = document
const WIDTH = 992 // 参考Bootstrap的响应式设计

export function useResize() {
  const route = useRoute()

  watch(route, () => {
    if (App.device === 'mobile' && App.sidebar.opened) {
      App.closeSidebar(false)
    }
  })

  const isMobile = () => {
    const rect = body.getBoundingClientRect()
    return rect.width - 1 < WIDTH
  }

  const resizeHandler = () => {
    if (!document.hidden) {
      const mobile = isMobile()
      App.toggleDevice(mobile ? 'mobile' : 'desktop')
      if (mobile) {
        App.closeSidebar(true)
      }
    }
  }

  onBeforeMount(() => {
    window.addEventListener('resize', resizeHandler)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler)
  })

  onMounted(() => {
    const mobile = isMobile()
    if (mobile) {
      App.toggleDevice('mobile')
      App.closeSidebar(true)
    }
  })
}
